/**
 * @Title: Upload.java
 * @Copyright (C) 2017 龙图软件
 * @Description:
 * @Revision History:
 * @Revision 1.0 2017-11-21  yuanchunci
 */
 

package com.ycc.fileTransfer.controller;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ycc.fileTransfer.entity.FormFile;
import com.ycc.fileTransfer.service.FileTransferService;
import com.ycc.uitl.ThumbnailUitl;

/**
 * @ClassName: Upload
 * @Description: Description of this class
 * @author <a href="mailto:XXX@qq.com">yuanchunci</a>于 2017-11-21 上午9:30:35
 */
@Controller
@RequestMapping(value="filetransfer")
public class FileTransferController extends HttpServlet{
	@Resource
	FileTransferService fileTransferService;
	
	@RequestMapping(value="/upload" ,method=RequestMethod.POST)
    public String upload(@RequestParam("file") MultipartFile file,HttpServletRequest request,HttpServletResponse response) throws Exception{
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        Properties pro = new Properties();
   	  InputStream in = this.getClass().getResourceAsStream("/uploadLocation.properties");
   	  String uploadPath="";
  	   try {
  	        pro.load(in);
  	 	} catch (IOException e) {
  	 		e.printStackTrace();
  	 	}finally{
  	 		in.close();
  	 	}
          if(pro!=null){
            uploadPath=pro.getProperty("uploadUrl");
            System.out.println(uploadPath);
          }
          File fileDir = new File(uploadPath);
          if(!fileDir.exists()){
          	fileDir.mkdir();
          }
		if(!file.isEmpty()) {  
		        Map p=new HashMap();
		        Map result=new HashMap();
		        String path=uploadPath+"/thum";
		        String typesStr="mpg,mpeg,avi,rm,rmvb,mov,wmv,asf,dat(VCD),asx,wvx,mpe,mpa,mp4,mp3";
				String type= Arrays.toString(ImageIO.getReaderFormatNames())+typesStr;
				String suffix=null;
		        result= ThumbnailUitl.thumbnail(file,uploadPath, uploadPath,uuid);
		        p.put("content", "");
		        p.put("filepath", result.get("filepath"));
				p.put("id", uuid);
				p.put("fileName",file.getOriginalFilename());
				if(file.getOriginalFilename().indexOf(".") > -1) {
				      suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
				 }
				if(type.indexOf(suffix)>-1){
					p.put("ThumbnailName", path+"/"+uuid+file.getOriginalFilename().substring(0, file.getOriginalFilename().indexOf(suffix))+"jpg");
				}else{
					p.put("ThumbnailName", "");

				}
				//Thread.currentThread().getContextClassLoader().getResource("").getPath();
				p.put("ThumbnailData", ThumbnailUitl.thumbnail(request,file, path, (String)result.get("filepath"),uuid));
				fileTransferService.insertOne(p);// 这里就把获得的byte字节文件数据做操作
		   }
		 return "redirect:show.html";    
    	
    }
	
	@RequestMapping(value="/show" ,method=RequestMethod.GET)
    public String show(HttpServletRequest request, HttpServletResponse response) throws Exception{
		Map p=new HashMap();
		List<FormFile> ls=fileTransferService.get(p);
		request.setAttribute("ls",  JSONArray.fromObject(ls));
		return "/file/show";    
    	
    }
	@RequestMapping(value="/showImge" ,method=RequestMethod.GET)
	public void showImge(HttpServletRequest request, HttpServletResponse response) throws Exception{
		 // 禁止图像缓存。
	    response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/png");
		ServletOutputStream sos = response.getOutputStream();
		Map param=new HashMap();
		param.put("id", request.getParameter("id"));
		List<FormFile> ls=fileTransferService.get(param);
		byte[] bb=ls.size()>0?ls.get(0).getThumbnail():null;
	    // 将图像输出到Servlet输出流中。
		sos.write(bb, 0, bb.length);
		sos.flush();
		sos.close();
	}
	
	
	
	@RequestMapping(value="/del" ,method=RequestMethod.GET)
	@ResponseBody
	public String  delete(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String id=request.getParameter("id");
		int i=fileTransferService.delete(id);
		System.out.println(i);
		return id;
    }  
	
	@RequestMapping(value="/toPaly" ,method=RequestMethod.GET)
	public String Topaly(HttpServletRequest request,HttpServletResponse response) throws Exception{
		request.setAttribute("id", request.getParameter("id"));
		return "/file/play";
    }  
	
	@RequestMapping(value="/paly" ,method=RequestMethod.GET)
	@ResponseBody
	public void  paly(HttpServletRequest request,HttpServletResponse response) throws Exception{
		Map param=new HashMap();
		param.put("id", request.getParameter("id"));
		List<FormFile> ls=fileTransferService.get(param);
		String srcPath="";
		if(ls.size()>0){
			 srcPath=ls.get(0).getFilepath();
			 File f=new File(srcPath);
	         FileInputStream is = new FileInputStream(f);
	         ByteArrayOutputStream bos = new ByteArrayOutputStream();
	         byte[] b = new byte[is.available()];
	     	 byte[] bb=null;
	         int n;
	         while ((n = is.read(b)) != -1)
	         {
	             bos.write(b, 0, n);
	         }
	         is.close();
	         bos.close();
	         bb = bos.toByteArray();
	        InputStream fis = new ByteArrayInputStream(bb);
	        // 创建输出流
	        OutputStream out = response.getOutputStream();
	        // 创建缓冲区
	        byte buffer[] = new byte[fis.available()];
	        int len = 0;
	        // 循环将输入流中的内容读取到缓冲区当中
	        while ((len = fis.read(buffer)) > 0) {
	            // 输出缓冲区的内容到浏览器，实现文件下载
	            out.write(buffer, 0, len);
	        }
	        // 关闭文件输入流
	        fis.close();
	        // 关闭输出流
	        out.close();
		}
    }  
}
